﻿using System.Diagnostics;
using System.Text;

namespace MG_POS_PC.Util
{
    public class ProcessExcuter
    {
        public static void Run(string exeFilePath, string args)
        {
            if (string.IsNullOrEmpty(exeFilePath) || !System.IO.File.Exists(exeFilePath))
            {
                throw new System.IO.FileNotFoundException();
            }


            Process p;
            p = new Process();
            p.StartInfo.FileName = exeFilePath;
            p.StartInfo.Arguments = args;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardOutput = true;
            int time = 5000;

            StringBuilder sbOut = new StringBuilder();
            StringBuilder sbError = new StringBuilder();

            try
            {
                p.Start();

                p.ErrorDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs e)
                {
                    sbError.Append(e.Data + "\r\n");
                });
                p.OutputDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs e)
                {
                    sbOut.Append(e.Data + "\r\n");
                });

                p.BeginErrorReadLine();
                p.BeginOutputReadLine();

                p.WaitForExit(time);
            }
            finally
            {
                if (p != null)
                {
                    p.Close();
                    p.Dispose();
                    p = null;
                }
            }
           
        }
    }
}
